from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.utils.decorators import method_decorator
from myapp.myser import *
#导入类视图
from django.views import View

from myapp.models import *
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from PIL import Image,ImageDraw

 # 导包
import redis

  # 定义IP地址和端口
host = '127.0.0.1'
port = 6379
  # 链接对象
r = redis.Redis(host=host,port=port)

import pymongo

#建立mongo的链接对象
mongo_client = pymongo.MongoClient(host='localhost',port=27017)

#导入bson
from bson import json_util as jsonb

  # 对结果集美化方法
def dictfetchall(cursor):
    # 获取游标描述
    desc = cursor.desciption

    return [
        dict(zip([col[0] for col in desc],row))

        for row in cursor.fetchall()

    ]

  # 商品关注接口(查询用户关注过的商品列表)
class UidFlow(View):
    def get(self,request):
        uid = request.GET.get('uid',None)
        # 建立游标对象
        cursor = connection.cursor()

        # 执行sql语句
        cursor.execute('select a.name from goods left join UserFlow b on a.id = b.gid where b.uid = %s' % str(uid))

        # 获取结果
        result = cursor.fetchall()

        # 返回结果 手动序列化
        return HttpResponse(json.dumps(result,ensure_ascii=False),
                            content_type='application/json')

# mongo存储商品评论
class MongoComment(APIView):
    def get(self, request):
        id = request.GET.get('id', None)
        uid = request.GET.get('uid', None)
        content = request.GET.get('content', None)

        # 建立数据库对象
        db = mongo_client.md
        # 建立表对象
        table = db.comment
        table.insert({'gid': str(id), 'content': content, 'uid': uid})
        return Response({
            'code': 200,
            'message': '评论成功'
        })

  # 评论列表
class CommentList(APIView):
    def get(self,request):
        # 商品id
        id = request.GET.get('id',None)
        # 查询评论
        comment = Comment.objects.filter(gid=str(id))
        # 序列化
        comment_ser = CommentSer(comment,Many=True)

        return Response(comment_ser.data)

  # 反序列化入库(商品评论)
class InsertComment(APIView):
    def post(self,request):

        uid = request.POST.get('uid',None)

        if r.get('uid'):
            return Response({'code': 403, 'message': '评论的太快了'})

        # 初始化参数
        comment = CommentSer(data=request.data)
        # 数据校验
        if comment.is_valid():
            # 数据入库
            comment.create(comment.data)

            # 插入评论标记
            r.set(str(uid),'123')
            r.expire(str(uid),30)

        return Response({'code':200,'message':'评论成功'})

# 修改商品标签接口
class UpdateTags(APIView):
    def get(self,request):
        # 接收参数
        id = request.GET.get('id', None)
        tags = request.GET.get('tags', None)
        tags = tags.split(',')
        # 建立数据库对象
        db = mongo_client.md
        # 添加表对象
        table = db.mytag
        # 直接修改
        table.update({'gid':str(id)},{'$set':{'tags':tags}})
        return Response({'msg':'修改成功'})



#获取商品标签接口
class GetTags(View):

	def get(self,request):

		id = request.GET.get("id",None)

		#建立数据库对象
		db = mongo_client.md
		#建立表对象
		table = db.mytag

		#查询数据
		res = table.find_one({"gid":str(id)})

		return HttpResponse(jsonb.dumps(res,ensure_ascii=False))




#商品标签添加接口
class InsertTags(APIView):

	def get(self,request):

		id = request.GET.get("id",None)
		tags = request.GET.get("tags",None)
		tags = tags.split(",")

		#建立数据库对象
		db = mongo_client.md
		#建立表对象
		table = db.mytag

		#排重操作
		#查询
		res = table.find({"gid":str(id)}).count()

		if res > 0:
			return Response({'message':'重复数据'})

		else:
			#入库操作
			table.insert({"gid":str(id),"tags":tags})

			return Response({'message':'入库成功'})

  # 商品信息接口
class GoodInfo(APIView):
    def get(self,request):
        id = int(request.GET.get('id',0))

        # 查询数据
        good = Goods.objects.get(id=id)

        # 序列化操作
        good_ser = GoodsSer(good)

        return Response(good_ser.data)

  # 商品列表页
class GoodsList(APIView):
    def get(self,request):
        # 当前页
        page = int(request.GET.get('page',1))
        # 一页有多少条上商品
        size = int(request.GET.get('size',1))

        # 定义从那开始切
        data_start = (page-1) * size
        #定义切到那儿
        data_end = page * size

        # 查询数据
        goodslist = Goods.objects.all()[data_start:data_end]
        # 查询总数量
        count = Goods.objects.count()
        # 序列化操作
        goods_ser = GoodsSer(goodslist,many=True)
        res = {}
        res['total'] = count
        res['data'] = goods_ser.data
        return Response(res)



  # 幻灯片接口
class PicsList(APIView):
    def get(self,request):

        # 查询数据
        pics = Pics.objects.filter().values('title','link','img')

        # 序列化对象
        pics_ser = Picsser(pics,many=True)

        return Response(pics_ser.data)

 # 插入幻灯片
class InsertGoods(APIView):
    def get(self,request):
        # 接收参数
        name = request.GET.get('name','null')
        desc = request.GET.get('desc','null')
        param = request.GET.get('param','null')
        care_id = request.GET.get('care_id','null')
        price = request.GET.get('price','null')
        img = request.GET.get('img', 'null')
        video = request.GET.get('video', 'null')

        #排重
        goods = Goods.objects.filter(name=name).first()
        if goods:
            res = {}
            res['code'] = 405
            res['message'] = '该活动已存在'
            return Response(res)

        # 入库
        goods = Goods(name=name,desc=desc,param=param,care_id=care_id,price=price,img=img,video=video)
        goods.save()

        # 查询商品id
        goods = Goods.objects.filter(name=name).first()

        res = {}
        res['code'] = 200
        res['id'] = goods.id
        res['message'] = '添加成功'
        return Response(res)


